<template>
  <div class="app-container" v-loading="loading">
    <el-form
      :model="fileFormData"
      :inline="true"
      label-width="110px"
      ref="addP"
      :rules="addPrules"
    >
      <el-divider content-position="left">基础信息</el-divider>
      <el-form-item label="配置类型" prop="configType">
        <el-select
          style="width: 215px"
          v-model="fileFormData.configType"
          @change="configTypeChange"
          :disabled="detail"
          placeholder="请选择配置类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in tableTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          />
        </el-select>
      </el-form-item>
      <br />
      <el-form-item
        label="平台名称"
        prop="platform"
        v-if="fileFormData.configType == 10"
      >
        <el-select
          v-model="fileFormData.platform"
          style="width: 215px"
          placeholder="请选择平台名称"
          filterable
          clearable
          :disabled="detail"
          @change="platformChange"
          size="small"
        >
          <el-option
            v-for="dict in platformList"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="店铺名称"
        prop="shopId"
        v-if="fileFormData.configType == 10"
      >
        <el-select
          v-model="fileFormData.shopId"
          placeholder="请选择店铺名称"
          clearable
          size="small"
          style="width: 215px"
          :disabled="
            detail ||
            fileFormData.platform == null ||
            fileFormData.platform == ''
          "
          filterable
          @change="shopChange"
          @focus="getListShop('', fileFormData.platform)"
          :remote-method="shopList"
        >
          <el-option
            v-for="item in shopList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <br />
      <el-form-item
        label="原始文件"
        prop="file"
        :rules="{
          required: true,
          message: '请导入平台订单原文件',
          trigger: 'change',
        }"
      >
        <el-tooltip
          class="item"
          effect="dark"
          content="请导入平台订单原文件"
          placement="top"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
        <el-upload
          :class="fileFormData.file.length >= 1 ? 'hide-upload' : ''"
          ref="upload"
          :http-request="uploadFile"
          :disabled="removeDisabled"
          :before-upload="beforeAvatarUpload"
          list-type="picture-card"
          headers="Content-Type: multipart/form-data"
          accept=".xls,.xlsx"
          :file-list="fileFormData.file"
          :on-change="handleFileSuccess1"
          :on-progress="handleAvatarSuccess"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.previewUrl"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                v-show="file.isImage"
                class="el-upload-list__item-preview"
                @click="handlePreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <i class="el-icon-download"></i>
              </span>
              <span
              v-if="!detail"
                class="el-upload-list__item-delete"
                @click="handleRemoveFiles(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
        <!-- <span v-if="!removeDisabled">
          <i style="color: red; font-size: 10px">
            提示：仅支持Excel格式文件上传，文件大小不超过20M
          </i>
        </span>
        <br />
        <el-link type="info" style="font-size: 12px" @click="importTemplate">{{
          "下载模板"
        }}</el-link> -->
      </el-form-item>
      <el-divider content-position="left">表单配置</el-divider>
      <div v-if="activate">
        <el-table v-loading="loading" :data="dataList" height="150px" border>
          <el-table-column
            v-for="item in headerList"
            align="center"
            :key="item.sort"
            prop="code"
            show-overflow-tooltip
            min-width="200"
          >
            <template slot="header">
              <span style="color: red" v-if="item.requireFlag">*</span>
              <span>{{ item.name }}</span>
            </template>
            <template slot-scope="scope">
              <el-select
                v-model="scope.row[item.name]"
                clearable
                placeholder="请选择"
                style="width: 170px"
                filterable
                :disabled="detail"
                @change="handleOutlayInput"
              >
                <el-option
                  v-for="dict in wsList"
                  :key="dict.header"
                  :label="dict.header"
                  :value="dict.header"
                  :disabled="dict.disabled"
                ></el-option>
                <!-- :disabled="dict.disabled" -->
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="reminder">
        注意：
        <br />
        1、请确认是否需要维护平台商品关系、平台仓库关系！
        <br />
        2、如需将订单真实推送至仓库发货，请额外配置以下选项：支付人身份证名称、身份证号、收货人、收货人电话、收货人省份、收货人城市、收货人县区、收货人详细地址、支付单号！
        <br />
        3、可前往查看字段说明：<a
          class="erpsop1"
          target="_blank"
          href="http://doc.fkmalls.com/pages/viewpage.action?pageId=8325024"
          ><span>
            <i
              class="el-icon-s-promotion"
              style="color: black; font-size: 18px"
            ></i> </span
        ></a>
      </div>
    </el-form>
    <!-- <div style="height: 150px"></div> -->
    <div class="submit_btn" style="z-index: auto">
      <div class="buttonBox">
        <el-button
          type="primary"
          @click="submit"
          :disabled="loading"
          v-if="!detail"
          >提交</el-button
        >
        <el-button @click="cancel" :disabled="loading">返回</el-button>
      </div>
    </div>
    <div v-if="activate"></div>
  </div>
</template>

<script>
import GoodsSupplier from "@/views/components/GoodsSupplier";
import { listData } from "@/api/system/dict/data";
import { uploadFile } from "@/api/system/file";
import { isImageUrl } from "@/utils/fkmalls";
import XLSX from "xlsx";
import download from "@/utils/download";
import { listShop } from "@/api/member/shop";

import {
  getTableHeadListByType,
  sysDynamicTableConfigAdd,
  sysDynamicTableConfigDetail,
  sysDynamicTableConfigUpdate,
  parseFileHeadList,
} from "@/api/common/importProfile";
export default {
  mounted() {},
  name: "AddImport",
  components: { GoodsSupplier },
  data() {
    return {
      // wsList: [],
      dataList: [{}],
      headerList: [],
      wsList: [],
      loading: false,
      activate: true,
      //平台
      platformList: [],
      //新增表单校验
      addPrules: {
        platform: [
          { required: true, message: "平台名称不能为空", trigger: "change" },
        ],
        shopId: [
          { required: true, message: "店铺名称不能为空", trigger: "change" },
        ],
      },
      fileFormData: {
        file: [],
      },
      tableTypeOptions: [],
      //店铺
      shopList: [],
      fileData: null,
      //表格头列表
      wsListArr :[]
    };
  },
  computed: {
    detail() {
      return this.$route.meta.detail;
    },
  },
  //触发回流
  activated() {
    this.activate = false;
    setTimeout(() => {
      this.activate = true;
    });
  },
  async created() {
    this.getDicts("sys_platform_type").then((res) => {
      // WEINI_HAIGOU
      // FKMALLS
      // DISTRIBUTOR
      let platformList = [];
      res.data.forEach((item) => {
        if (
          item.dictValue == "WEINI_HAIGOU" ||
          item.dictValue == "FKMALLS" ||
          item.dictValue == "DISTRIBUTOR"
        ) {
          platformList.push(item);
        }
      });
      this.platformList = platformList;
    });
    this.getDicts("sys_dynamic_table_type").then((response) => {
      this.tableTypeOptions = response.data;
    });
    if (this.$route.params.id) {
      this.loading = true;
      sysDynamicTableConfigDetail(this.$route.params.id).then((res) => {
        console.log(res);
        this.headerList = res.data.tableHeadList.sort(this.objectSort("sort"));
        // this.dataList
        this.dataList = [{ ...JSON.parse(res.data.mapRel) }];
        //清空表单校验
        this.$refs.addP.resetFields();
        this.fileFormData.configType = res.data.configType;
        //获取平台店铺
        this.fileFormData.platform = res.data.uniqueKey.split("-")[0];
        this.fileFormData.shopId = res.data.uniqueKey.split("-")[1];
        this.fileFormData.platformName = res.data.uniqueKeyName.split("-")[0];
        this.fileFormData.shopName = res.data.uniqueKeyName.split("-")[1];
        this.fileFormData.file = [...res.data.fileInfo];
        if(res.data.fileInfo.length>0){
          this.fileFormData.fileId = res.data.fileInfo[0].id
        }
        //获取表格表头数据
          this.wsList = res.data.fileHeadList||[];
          let wsList = [];
        this.wsListArr = res.data.fileHeadList||[];
        res.data.fileHeadList.forEach((item) => {
          if (item) {
            let item1 = { header: item };
            wsList.push({ ...item1 });
          }
        });
        this.wsList = [...wsList];
        this.setDisabled(this.wsList, this.dataList);
        if (this.fileFormData.file) {
          this.fileFormData.file.forEach((item) => {
            this.setPreviewUrl(item);
          });
        }
        this.getListShop("", this.fileFormData.platform);
        this.activate = false;
        setTimeout(() => {
          this.activate = true;
        });
        this.fileFormData = { ...this.fileFormData };
        this.loading = false;
      });
    } else {
      this.loading = true;
      getTableHeadListByType(10).then((res) => {
        this.headerList = res.data.sort(this.objectSort("sort"));
        let mappingrekl = {};
        this.headerList.forEach((item) => {
          mappingrekl[item.name] = null;
        });
        this.dataList = [mappingrekl];
        this.activate = false;
        setTimeout(() => {
          this.activate = true;
        });
        this.loading = false;
      });
    }
  },
  methods: {
    objectSort(property) {
      return function (Obj1, Obj2) {
        return Obj1[property] - Obj2[property];
      };
    },
    configTypeChange() {
      this.fileFormData.platformName = null;
      this.fileFormData.platform = null;
      this.fileFormData.shopId = null;
      this.fileFormData.shopName = null;
      this.fileFormData = { ...this.fileFormData };
    },
    //获取店铺
    async getListShop(name, platform) {
      let response = await listShop({ name: name, platform: platform });
      this.shopList = response.data;
    },
    handleOutlayInput() {
      this.setDisabled(this.wsList, this.dataList);
    },
    platformChange(v) {
      this.platformList.forEach((item) => {
        if (item.dictValue == v) {
          this.fileFormData.platformName = item.dictLabel;
        }
      });
      this.fileFormData.shopId = null;
      this.fileFormData.shopName = null;
      this.fileFormData = { ...this.fileFormData };
      this.getListShop("", v);
    },
    shopChange(v) {
      this.shopList.forEach((item) => {
        if (item.id == v) {
          this.fileFormData.shopName = item.name;
        }
      });
    },
    //获取表头数据
    getParseFileHeadList(formData) {
      parseFileHeadList(formData).then((res) => {
        let wsList = [];
        console.log(res.data);
        this.wsListArr = res.data;
        res.data.forEach((item) => {
          if (item) {
            let item1 = { header: item };
            wsList.push({ ...item1 });
          }
        });
        this.wsList = [...wsList];
        if (this.wsList.length == 0) {
          this.handleRemoveFiles();
        }
        if (this.$route.params.id) {
          this.setDisabled(this.wsList, this.dataList);
        }
      });
    },
    //输入框选项禁用方法
    setDisabled(arr1, arr2) {
      let arr = [];
      arr1.forEach((item, index) => {
        arr2.some((item1) => {
          for (let i in item1) {
            if (item1[i] == item.header) {
              //获取禁用的字段
              arr = [...arr, item1[i]];
            }
          }
        });
      });
      //禁用选中数据
      arr1.forEach((item, index) => {
        if (arr.some((item1) => item1 == item.header)) {
          arr1[index] = { ...item, disabled: true };
        } else {
          arr1[index] = { ...item, disabled: false };
        }
      });
    },
    //报价方式选框
    handleSeleQuote(e) {},
    beforeAvatarUpload(file) {
      let fileName = file.name;
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (
        lastName.toLowerCase() !== ".xls" &&
        lastName.toLowerCase() !== ".xlsx"
      ) {
        this.$message.error("文件必须为.xls .xlsx类型");
        return;
      }
      // 限制上传文件的大小
      let isLt = file.size / 1024 / 1024 / 20 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不得大于20MB!");
      }
      if (this.fileFormData.file.length > 0) {
        this.$message.error("只能上传一个文件");
        isLt = false;
      }
      return isLt;
    },
    // 预览图片
    handlePreview(file) {
      if (!isImageUrl(file.url)) {
        window.open(file.url, "_blank");
      } else {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    },
    // 下载图片
    handleDownload(file) {
      //window.open(file.url)
      // download(file.path, file.name);
      // download(file.url, file.name);
      window.location.href = file.url;
    },
    //删除附件
    handleRemoveFiles(file) {
      // this.__.remove(this.fileFormData.file, true);
      this.fileFormData.previewUrl = null;
      this.fileFormData.file = [];
      this.wsList = [];
      this.fileFormData.raw = null;
      if (this.dataList.length > 0) {
        this.headerList.forEach(item1=>{
          this.dataList.forEach((item) => {
          if(item[item1.name]){
            item[item1.name]=null;
            item={...item}
          }
        });
        this.dataList = [...this.dataList];
        })
      }
    },
    // handleFileSuccess1(file) {
    //   console.log(file, 11111);
    //   this.fileData = file;
    //   this.readExcel();
    // },
    uploadFile(options) {
      const formData = new FormData();
      formData.append("file", options.file);
      this.fileFormData.raw = options.file;
      console.log(options.file);
      //解析表格
      //   this.readExcel();
      this.getParseFileHeadList(formData);
      // parseFileHeadList(formData).then((res) => {
      //   let wsList = [];
      //   console.log(res.data);
      //   res.data.forEach((item) => {
      //     if (item) {
      //       let item1 = { header: item };
      //       wsList.push({ ...item1 });
      //     }
      //   });
      //   this.wsList = [...wsList];
      //   if (this.wsList.length == 0) {
      //     this.handleRemoveFiles();
      //   }
      //   if (this.$route.params.id) {
      //     this.setDisabled(this.wsList, this.dataList);
      //   }
      // });
      this.loading = true;
      uploadFile(formData)
        .then((response) => {
          this.fileFormData.fileId = response.data.id;
          if (response.data instanceof Array) {
            response.data.forEach((data) => {
              this.setPreviewUrl(data);
              this.fileFormData.file.push(data);
            });
          } else {
            this.setPreviewUrl(response.data);
            this.fileFormData.file.push(response.data);
          }

          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    resetFilesData() {
      this.fileFormData.platform = null;
      this.fileFormData.file = [];
      this.removeDisabled = false;
      this.resetForm("fileForm");
      this.fileFormData = { ...this.fileFormData };
    },
    //设置图片预览
    setPreviewUrl(file) {
      file.previewUrl = file.url;
      file.isImage = true;
      if (!isImageUrl(file.url)) {
        file.previewUrl = require("@/assets/images/file.jpg");
        file.isImage = false;
      }
    },
    // readExcel() {
    //   const files = this.fileData;
    //   if (!files) {
    //     // 没有文件
    //     return false;
    //   } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
    //     this.$message.error("请上传xls或者xlsx文件");
    //     return false;
    //   }
    //   const fileReader = new FileReader();
    //   fileReader.onload = (e) => {
    //     try {
    //       const data = e.target.result;
    //       const workbook = XLSX.read(data, {
    //         type: "binary",
    //       });
    //       let wsList = [];
    //       workbook.Strings.forEach((item) => {
    //         if (item.h) {
    //           let item1 = { header: item.h };
    //           wsList.push({ ...item1 });
    //         }
    //       });
    //       this.wsList = [...wsList];
    //       if(this.$route.params.id){
    //         this.setDisabled(this.wsList, this.dataList);
    //       }
    //       console.log(wsList, 213213213);
    //     } catch (e) {
    //       return false;
    //     }
    //   };
    //   fileReader.readAsBinaryString(files.raw);
    // },
    //确定按钮
    submit() {
      console.log(this.wsList, this.wsList.length);
      if (this.wsList.length == 0) {
        this.$message.error("请导入平台订单原文件");
        return;
      }
      //表单校验
      this.$refs.addP.validate(async (valid) => {
        if (valid) {
          try {
            this.headerList.forEach((item) => {
              if (
                item.requireFlag == true &&
                (this.dataList[0][item.name] == null ||
                  this.dataList[0][item.name] == "")
              ) {
                throw `表头名称为 '${item.name}' 的数据项不能为空`;
              }
            });
            console.log(this.dataList[0]);
            let uniqueKeyList = [
              {
                key: this.fileFormData.platform,
                name: this.fileFormData.platformName,
              },
              {
                key: this.fileFormData.shopId,
                name: this.fileFormData.shopName,
              },
            ];
            if (this.$route.params.id) {
              sysDynamicTableConfigUpdate({
                mappingRel: this.dataList[0],
                uniqueKeyList: uniqueKeyList,
                configType: this.fileFormData.configType,
                id: this.$route.params.id,
                fileId: this.fileFormData.fileId,
                fileHeadList:this.wsListArr
              })
                .then((res) => {
                  console.log(res);
                  this.$message.success("修改成功");
                  this.loading = false;
                  this.cancel();
                })
                .catch((err) => {
                  this.loading = false;
                });
            } else {
              console.log(this.fileFormData);
              sysDynamicTableConfigAdd({
                mappingRel: this.dataList[0],
                uniqueKeyList: uniqueKeyList,
                configType: this.fileFormData.configType,
                fileId: this.fileFormData.fileId,
                fileHeadList:this.wsListArr
              })
                .then((res) => {
                  console.log(res);
                  this.$message.success("新增成功");
                  this.loading = false;
                  this.cancel();
                })
                .catch((err) => {
                  this.loading = false;
                });
            }
          } catch (err) {
            this.$message.error(err);
          }
          // this.loading = true;
        }
      });
    },
    //取消
    cancel() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    },
  },
};
</script>

<style lang="scss" scoped>
.divTabulation {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.divTabulation > P {
  margin-right: 5px;
}
::v-deep .cell {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.settlementPriceRange {
  width: 100%;
  height: 300px;
}
::v-deep .filter-tree {
  height: 64vh;
}
::v-deep .el-dialog__body {
  overflow: hidden;
}
::v-deep .el-upload-dragger {
  width: 70vh;
  margin: 0 auto;
}
::v-deep .el-step__description {
  margin-top: 10px;
}
::v-deep .el-divider__text {
  font-weight: 550;
  font-size: 15px;
}
.upload {
  margin-left: 40px;
}
.submit_btn {
  margin-top: 19px;
  position: sticky;
  display: flex;
  bottom: 0;
  justify-content: center;
}
::v-deep .hide-upload > div {
  display: none;
}
.reminder {
  color: red;
  margin-top: 10px;
  margin-left: 20px;
  font-size: 14px;
}
</style>
